package local.blueheart.data.springdatademo.service.impl;

import local.blueheart.data.springdatademo.config.Constant;
import local.blueheart.data.springdatademo.domain.task.ScheduleJob;
import local.blueheart.data.springdatademo.domain.task.TaskEntity;
import local.blueheart.data.springdatademo.exception.DataTransferException;
import local.blueheart.data.springdatademo.repository.TaskRepository;
import local.blueheart.data.springdatademo.service.TaskService;
import local.blueheart.data.springdatademo.util.QuartzManager;
import local.blueheart.data.springdatademo.util.ScheduleJobUtils;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 任务管理服务
 */
@Service
public class TaskServiceImpl implements TaskService {

    private static final Logger LOGGER = LoggerFactory.getLogger(TaskServiceImpl.class);

    @Autowired
    private TaskRepository taskRepository;

    @Autowired
    private QuartzManager quartzManager;

    @Override
    public TaskEntity get(Long id) {
        return taskRepository.getOne(id);
    }

    @Override
    public Page<TaskEntity> list(Integer page, Integer size) {
        Pageable pageable = PageRequest.of(page,size);
        return taskRepository.findAll(pageable);
        //return taskRepository(page,size);
    }

    @Override
    public List<TaskEntity> list() {
        return taskRepository.findAll();
    }

    @Override
    public int count() {
        return (int) taskRepository.count();
    }

    @Override
    @Transactional
    public int save(TaskEntity taskScheduleJob) {
        try {
            taskRepository.save(taskScheduleJob);
        }catch (Exception e){
            LOGGER.error("保存出错",e);
            return 0;
        }finally {

        }
        return 1;
    }

    @Override
    @Transactional
    public int update(TaskEntity taskScheduleJob) {
        try{
            taskRepository.saveAndFlush(taskScheduleJob);
        }catch (Exception e){
            LOGGER.error("更新出错",e);
            return 0;
        }
        return 1;
    }

    @Override
    @Transactional
    public int remove(Long id) {
        try {
            taskRepository.deleteById(id);
        }catch (Exception e){
            LOGGER.error("删除出错",e);
            return 0;
        }
        return 1;
    }

    @Override
    public int batchRemove(Long[] ids) {
        for(Long id:ids){
            remove(id);
        }
        return ids.length;
    }

    @Override
    public void initSchedule() throws DataTransferException {
        List<TaskEntity> taskEntities = list();
        for(TaskEntity taskEntity:taskEntities){
            if("1".equals(taskEntity.getJobStatus())){
                ScheduleJob job = ScheduleJobUtils.entityToData(taskEntity);
                quartzManager.addJob(job);
            }
        }
    }

    @Override
    public void changeStatus(Long jobId, String cmd) throws DataTransferException {
        TaskEntity taskEntity = get(jobId);
        if(taskEntity == null){
            return;
        }
        if(Constant.STATUS_RUNNING_STOP.equals(cmd)){
            try {
                quartzManager.deleteJob(ScheduleJobUtils.entityToData(taskEntity));
                taskEntity.setJobStatus(ScheduleJob.STATUS_NOT_RUNNING);
            } catch (SchedulerException e) {
                throw new DataTransferException(e);
            }
        }else {
            if(!Constant.STATUS_RUNNING_START.equals(cmd)){

            }else {
                taskEntity.setJobStatus(ScheduleJob.STATUS_RUNNING);
                quartzManager.addJob(ScheduleJobUtils.entityToData(taskEntity));
            }
        }
        update(taskEntity);
    }


    @Override
    public void updateCron(Long jobId) throws DataTransferException {
        TaskEntity taskEntity = get(jobId);
        if(taskEntity==null){
            return;
        }
        if(ScheduleJob.STATUS_RUNNING.equals(taskEntity.getJobStatus())){
            try {
                quartzManager.updateJobCron(ScheduleJobUtils.entityToData(taskEntity));
            } catch (SchedulerException e) {
                throw new DataTransferException(e);
            }
        }
        update(taskEntity);

    }

    @Override
    public void runOneById(Long id) throws DataTransferException {
        TaskEntity taskEntity = get(id);
        if(taskEntity==null){
            return;
        }
        ScheduleJob job = ScheduleJobUtils.entityToData(taskEntity);
        try {
            quartzManager.runAJobNow(job);
        } catch (SchedulerException e) {
            LOGGER.error("运行一次出错",e);
            throw new DataTransferException(e);
        }
    }


}
